package com.basic.library.binding.viewadapter.radiogroup;


import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.databinding.BindingAdapter;

import com.basic.library.binding.command.BindingCommandAbstract;
import com.basic.library.binding.command.BindingCommandBean;

public class ViewAdapter {
    @BindingAdapter(value = {"onCheckedChangedCommand"}, requireAll = false)
    public static <T> void onCheckedChangedCommand(final RadioGroup radioGroup, final BindingCommandAbstract<T> bindingCommand) {
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
//                RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
            RadioButton rb = group.findViewById(checkedId);
            if (bindingCommand.mType == Integer.class || bindingCommand.mType == null) {
                Integer id = checkedId;
                if (rb == null || !rb.isChecked())
                    id = -1;
                bindingCommand.execute((T) id);
            } else {
                String text = null;
                if (rb != null) {
                    if (rb.isChecked())
                        if (rb.getTag() != null) {
                            text = rb.getTag().toString();
                            if (bindingCommand.mType == BindingCommandBean.class) {
                                bindingCommand.execute((T) new BindingCommandBean(checkedId, text));
                            } else
                                bindingCommand.execute((T) text);
                        } else {
                            text = rb.getText().toString();
                            if (bindingCommand.mType == BindingCommandBean.class) {
                                bindingCommand.execute((T) new BindingCommandBean(checkedId, text));
                            } else
                                bindingCommand.execute((T) text);
                        }
                    else if (rb.getTag() != null) {
                        if (bindingCommand.mType == BindingCommandBean.class) {
                            bindingCommand.execute((T) new BindingCommandBean(-1, null));
                        } else
                            bindingCommand.execute((T) "");
                    } else {
                        if (bindingCommand.mType == BindingCommandBean.class) {
                            bindingCommand.execute((T) new BindingCommandBean(-1, null));
                        } else
                            bindingCommand.execute((T) "");
                    }
                }
            }
        });
    }

    @BindingAdapter(value = {"clearCheck"}, requireAll = false)
    public static <T> void clearCheck(final RadioGroup radioGroup, final boolean clear) {
        if (clear)
            radioGroup.clearCheck();
    }
}
